/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head == NULL) {
            return head;
        }

        ListNode *cur = head;
        ListNode *tail = head;
        ListNode *pre = NULL;
        for (int i = 0; tail && i < n - 1; ++i) {
            tail = tail->next;
        }
        if (tail == NULL) {
            return head;
        }
        while (tail->next) {
            pre = cur;
            cur = cur->next;
            tail = tail->next;
        }
        if (pre == NULL) { // remove the head
            head = head->next;
        } else {
            pre->next = cur->next;
        }
        return head;

    }
};
